// PackageGatewayController.java
package com.example.gymlearning.controller;

import com.example.gymlearning.dto.KnowledgePackageDTO;
import com.example.gymlearning.entity.KnowledgePackage;
import com.example.gymlearning.entity.QuizQuestion;
import com.example.gymlearning.entity.UserPackageProgress;
import com.example.gymlearning.service.KnowledgePackageService;
import com.example.gymlearning.service.PackageGatewayService;
import com.example.gymlearning.service.UserProgressService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Slf4j
@Controller
@RequestMapping("/package/gateway")
@RequiredArgsConstructor
public class PackageGatewayController {

    private final KnowledgePackageService knowledgePackageService;
    private final PackageGatewayService packageGatewayService;
    private final UserProgressService userProgressService;

    /**
     * 知识包闯关准备页面
     */
    @GetMapping("/prepare")
    public String preparePackageGateway(@RequestParam Long packageId,
                                        @RequestParam(required = false) Long userId,
                                        Model model) {
        try {
            // 获取当前用户ID（实际项目中从session或token获取）
            Long currentUserId = getCurrentUserId(userId);

            // 获取知识包信息
            KnowledgePackageDTO knowledgePackage = knowledgePackageService.getById(packageId);
            if (knowledgePackage == null) {
                return "redirect:/knowledge/gym?error=知识包不存在";
            }

            // 获取用户进度
            UserPackageProgress progress = userProgressService.getPackageProgress(currentUserId, packageId);
            if (progress == null) {
                return "redirect:/knowledge/gym?error=请先学习该知识包的内容";
            }

            // 检查是否解锁
            if (!userProgressService.isPackageGatewayUnlocked(currentUserId, packageId)) {
                model.addAttribute("notUnlocked", true);
                model.addAttribute("completedPoints", progress.getCompletedPoints());
                model.addAttribute("totalPoints", progress.getTotalPoints());
            } else {
                // 获取闯关统计信息
                Map<String, Object> stats = packageGatewayService.getPackageGatewayStats(packageId);
                model.addAttribute("stats", stats);
            }

            model.addAttribute("package", knowledgePackage);
            model.addAttribute("progress", progress);
            model.addAttribute("packageId", packageId);

            log.info("加载知识包闯关准备页面: packageId={}, userId={}", packageId, currentUserId);

            return "package/gateway-prepare";

        } catch (Exception e) {
            log.error("加载知识包闯关准备页面失败: {}", e.getMessage(), e);
            return "redirect:/knowledge/gym?error=加载失败";
        }
    }

    /**
     * 开始知识包闯关
     */
    @GetMapping("/start")
    public String startPackageGateway(@RequestParam Long packageId,
                                      @RequestParam(required = false) Long userId,
                                      Model model) {
        try {
            Long currentUserId = getCurrentUserId(userId);

            // 创建闯关会话
            Long sessionId = packageGatewayService.createPackageGatewaySession(currentUserId, packageId);

            // 获取题目
            List<QuizQuestion> questions = packageGatewayService.getPackageGatewayQuestions(sessionId);

            model.addAttribute("sessionId", sessionId);
            model.addAttribute("questions", questions);
            model.addAttribute("packageId", packageId);
            model.addAttribute("isPackageGateway", true);

            log.info("开始知识包闯关: packageId={}, userId={}, 题目数量={}", packageId, currentUserId, questions.size());

            return "practice/gateway-session"; // 复用知识点闯关的答题页面

        } catch (Exception e) {
            log.error("开始知识包闯关失败: {}", e.getMessage(), e);
            return "redirect:/package/gateway/prepare?packageId=" + packageId + "&error=" + e.getMessage();
        }
    }

    /**
     * 提交知识包闯关答案
     */
    @PostMapping("/submit")
    public String submitPackageGateway(@RequestParam Long sessionId,
                                       @RequestParam Long packageId,
                                       @RequestParam Integer score,
                                       @RequestParam Integer totalQuestions,
                                       @RequestParam Integer correctAnswers,
                                       Model model) {
        try {
            // 完成闯关
            boolean isPassed = packageGatewayService.completePackageGateway(sessionId, score, correctAnswers, totalQuestions);

            model.addAttribute("isPassed", isPassed);
            model.addAttribute("score", score);
            model.addAttribute("totalQuestions", totalQuestions);
            model.addAttribute("correctAnswers", correctAnswers);
            model.addAttribute("packageId", packageId);
            model.addAttribute("isPackageGateway", true);

            log.info("提交知识包闯关: sessionId={}, 得分={}/{}, 通过={}", sessionId, score, totalQuestions, isPassed);

            return "package/gateway-result";

        } catch (Exception e) {
            log.error("提交知识包闯关失败: {}", e.getMessage(), e);
            return "redirect:/package/gateway/prepare?packageId=" + packageId + "&error=提交失败";
        }
    }

    /**
     * 获取当前用户ID（模拟方法，实际项目中替换为真实实现）
     */
    private Long getCurrentUserId(Long userId) {
        // 实际项目中从Session、Token或SecurityContext中获取
        // 这里为了演示，使用传入的userId或默认值
        return userId != null ? userId : 1L; // 默认用户ID
    }
}